#!/usr/bin/env python

#  Copyright 2007, Benjamin Feng
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#   1. Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#   2. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#   3. The name of the author may not be used to endorse or promote products
#      derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


import sys
import os

from .core import TargetNotFoundException, Tasklist


class MakepyfileNotFoundException(Exception):
    pass


def get_first_module(module_names):
    curpath = os.path.abspath(os.path.curdir)
    if curpath not in sys.path:
        sys.path.insert(0, curpath)

    for module_name in module_names:
        try:
            module = __import__(module_name)
        except ImportError:
            pass
        else:
            sys.path.remove(curpath)
            return module

    raise ImportError


def parse_args(args):
    targets = []
    options = []
    kwoptions = {}
    for arg in args:
        if arg.startswith('--'):
            key, sep, value = arg[2:].partition('=')
            kwoptions[key] = value if sep else True
        elif arg.startswith('-'):
            options.append(arg[1:])
        else:
            targets.append(arg)

    return targets, options, kwoptions


def run_from_command_line():
    module_names = ['makepyfile', 'Makepyfile']

    try:
        module = get_first_module(module_names)
    except ImportError:
        print 'No makepyfile found (looking for %s). Aborting.' % module_names
    else:
        tasklist = Tasklist.from_module(module)
        targets, options, kwargs = parse_args(sys.argv[1:])
        if not options and not targets:
            tasklist.run_tasks(kwargs=kwargs)
        else:
            tasklist.run_options(options)
            tasklist.run_tasks(targets)
